package vn.com.vega.chacha.v2;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.Appinstant.RegisterListener;
import vn.com.vega.music.clientserver.JsonAuth;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.objects.Package;
import vn.com.vega.music.player.ChaChaProgressDialog;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.custom.ChaChaDialog;
import vn.com.vega.music.view.custom.TextBox;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;

public class LoginActivity extends ActivityBase {
	public static final String NEED_AUTHENTICATION = "Need Authentication";

	private static final int LOGIN_SUCCESS = 0;
	private static final int LOGIN_FAILED = -1;
	private static final int AUTH_FAILED = -2;
	private static final int NO_NETWORK = -3;
	private static final int LOGIN_FAILED_401 = 401;
	private static final int DUPLICATED_PACKAGE = -5;

	private static final int GET_PACKAGE_SUCCESS = 1;
	private static final int GET_PACKAGE_FAILED = 2;
	private static final int SUBSCRIBE_SUCCESS = 3;
	private static final int SUBSCRIBE_FAILED = 4;

	private static final int SEND_SMS = -4;

	private static String ERROR_MSG = "";

	private String SMS_TO = "1226";
	private String SMS_BODY = "MK";

	private TextBox usernameField;
	private TextBox passwordField;
//	private Dialog dialog;
//	private Dialog subDialog;

	// private LinearLayout rememberMeLayout;
	// private CheckBox cb_remember_pass;

	private Button loginBtn/* , getPassBtn, registerBtn *//* , trialBtn */;
	private View getPassBtn, registerBtn;
	private ImageButton mExitBtn;

	private DataStore dataStore;

	String username = "";
	String password = "";

	String oldUsername = "";
	String oldPassword = "";

	boolean needAuthentication = false;
//	boolean isLogout = false;

	private Package selectedPackage;

	// private boolean isViettel = true;

	private ArrayList<Package> packages = null;

	private String registerMessage = "";

	private Appinstant mApp;

	private ChaChaProgressDialog mProgressDialog;

	static class LoginHandler extends Handler {
		WeakReference<LoginActivity> loginAct;

		public LoginHandler(LoginActivity act) {
			// TODO Auto-generated constructor stub
			loginAct = new WeakReference<LoginActivity>(act);
		}

		@Override
		public void handleMessage(Message msg) {
			LoginActivity login = loginAct.get();
			if (login == null) {
				return;
			}

			if (login.mProgressDialog != null
					&& login.mProgressDialog.isShowing())
				login.mProgressDialog.dismiss();
			switch (msg.what) {
			case NO_NETWORK:
				login.showAlert(login.getString(R.string.no_network_connection));
				break;
			case LOGIN_SUCCESS:
				// open Music page
				login.removeLogoutStickyBroadCast();
				Intent intent = new Intent(login.getApplicationContext(),
						MainScreen.class);
				login.dataStore.setConfig(Const.KEY_IS_LOGOUT, "false");
				login.startActivity(intent);
				login.finish();
				break;

			case DUPLICATED_PACKAGE:
				login.showAlert(login
						.getString(R.string.subcribe_duplicated_package));
				break;

			case LOGIN_FAILED:
				// forgetPass.setVisibility(TextView.VISIBLE);
				// Tuantm - Fix progress dialog 's still shown when login fail
				login.mProgressDialog.dismiss();
				// End
				login.showAlert(login
						.getString(R.string.login_screen_error_login_unsuccessfully));
				break;

			case LOGIN_FAILED_401:
				login.mProgressDialog.dismiss();
				if (Util.checkStringIsemptyOrNull(ERROR_MSG)) {
					ERROR_MSG = login
							.getString(R.string.login_screen_error_login_unsuccessfully);
				}
				login.showAlert(ERROR_MSG);
				break;

			case AUTH_FAILED:
				// Tuantm
				login.mProgressDialog.dismiss();
				// End
				login.showAlert(login
						.getString(R.string.login_screen_error_authenticate_unsuccessfully));
				break;
			case GET_PACKAGE_FAILED:
				login.mProgressDialog.dismiss();
				login.showAlert(login
						.getString(R.string.login_screen_no_package));
				break;
			case SUBSCRIBE_FAILED:
				login.mProgressDialog.dismiss();
				if (login.registerMessage.trim().equals(""))
					login.showAlert(login
							.getString(R.string.login_screen_subscribe_failed));
				else
					login.showAlert(login.registerMessage);
				break;
			case SUBSCRIBE_SUCCESS:
				login.mProgressDialog.dismiss();
				// enter app
				// loginAgain();
				// open Music page
				Intent i = new Intent(login.getApplicationContext(),
						MainScreen.class);
				login.startActivity(i);
				login.finish();
				break;
			case SEND_SMS:
				login.mProgressDialog.dismiss();
				break;
			// case GET_PACKAGE_SUCCESS:
			// mProgressDialog.dismiss();
			// if (packages != null) {
			// if (packages.size() == 1) {
			// selectedPackage = packages.get(0);
			// if (selectedPackage != null)
			// showSMSDialog();
			// } else if (packages.size() > 1) {
			// showPackageDialog();
			// }
			// }
			// break;
			}
		}
	}

	private LoginHandler mHandler = new LoginHandler(LoginActivity.this);


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mApp = (Appinstant) getApplication();

		oldUsername = "";
		oldPassword = "";
		dataStore = DataStore.getInstance();
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			needAuthentication = bundle.getBoolean(NEED_AUTHENTICATION);
		}

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login_screen);
		
		loginBtn = (Button) findViewById(R.id.bt_login);
		getPassBtn = findViewById(R.id.view_get_password);
		registerBtn = findViewById(R.id.view_register);
		mExitBtn = (ImageButton) findViewById(R.id.bt_exit);
		mExitBtn.setOnClickListener(onExitListener);
		// if (Appinstant.canTrialFuntion()) {
		// trialBtn = (Button) findViewById(R.id.login_screen_trial_btn);
		// trialBtn.setOnClickListener(onTrialListener);
		// trialBtn.setVisibility(View.VISIBLE);
		// }

		loginBtn.setOnClickListener(onLoginBtnListener);
		getPassBtn.setOnClickListener(onGetPassBtnListener);
		registerBtn.setOnClickListener(onRegisterBtnListener);

		usernameField = (TextBox) findViewById(R.id.textBox_account);
		passwordField = (TextBox) findViewById(R.id.textBox_password);
		usernameField.setTextColor("#116E9D");
		passwordField.setTextColor("#116E9D");
		passwordField.setIsPassword(true);
		usernameField.setTextHintColor("#666666");
		passwordField.setTextHintColor("#666666");
		usernameField.setTextHint(getString(R.string.login_screen_username));
		passwordField.setTextHint(getString(R.string.login_screen_password));
		passwordField.setBackground(R.drawable.bg_login_edittext);
		usernameField.setBackground(R.drawable.bg_login_edittext);

		oldUsername = dataStore.getMsisdn();
		oldPassword = dataStore.getSavedPassword();
		usernameField.setText(oldUsername);
		passwordField.setText(oldPassword);

		// For development only
		// usernameField.setText("client_dev");
		// passwordField.setText("123456");

		// if (isLogout) {
		// usernameField.setText("");
		// passwordField.setText("");
		// }

	}

//	View.OnClickListener onTrialListener = new OnClickListener() {
//
//		@Override
//		public void onClick(View v) {
//			// TODO Auto-generated method stub
//			// doRegisterTrial();
//			final ChaChaProgressDialog progressDialog = new ChaChaProgressDialog(
//					LoginActivity.this);
//			progressDialog.setTimeAutoHide(999999);
//			Thread registertrials = new Thread() {
//				@Override
//				public void run() {
//					// mApp.doRegisterTrial(LoginActivity.this, mHandler,
//					// progressDialog);
//					mApp.registerTrial(LoginActivity.this, mHandler,
//							progressDialog, true);
//				}
//			};
//			registertrials.start();
//		}
//	};

	View.OnClickListener closeRegisterClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			ChaChaDialog dialog = (ChaChaDialog) v.getTag();
			dialog.dismiss();
			onRegisterFailListener();
		}
	};

	View.OnClickListener onExitListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			finish();
		}
	};

	OnClickListener onLoginBtnListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			doLogin(null);
		}
	};

	OnClickListener onGetPassBtnListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			doGetPass(null);
		}
	};

	OnClickListener onRegisterBtnListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			// doRegister();
			mApp.register(LoginActivity.this, null, mHandler, false,
					registerListener);
		}
	};


	@Override
	public void onDestroy() {
		super.onDestroy();
		removeLogoutStickyBroadCast();
	}

	private void showAlert(String message) {
		// AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
		// alertDialog.setTitle(getText(R.string.dialog_notification));
		// alertDialog.setMessage(message);
		// alertDialog.setButton("Đóng", new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dialog.dismiss();
		// }
		// });
		// alertDialog.show();
		//
		ChaChaDialog dialogAlert = new ChaChaDialog(this, null);
		dialogAlert.setTitle(getText(R.string.dialog_notification));
		dialogAlert.setMessage(message);
		dialogAlert.addDefaultOkBtn("Đóng");
		dialogAlert.show();
	}

	private boolean checkLoginInfo(String username, String password) {
		if (username == null || username.equalsIgnoreCase("")) {
			showAlert(getString(R.string.login_screen_error_username_null));
			return false;
		}

		if (password == null || password.equalsIgnoreCase("")) {
			showAlert(getString(R.string.login_screen_error_password_null));
			return false;
		}

		if (username.trim().length() == 0 || password.trim().length() == 0) {
			showAlert(getString(R.string.login_screen_error_login_unsuccessfully));
			return false;
		}

		return true;
	}

	public void doLogin(View view) {
		username = usernameField.getText().toString();
		password = passwordField.getText().toString();

		if (!checkLoginInfo(username, password)) {
			return;
		}
		// dataStore.setConfig(Const.KEY_REMEMBER_ME,
		// cb_remember_pass.isChecked() == true ? "true" : "false");
		Thread doLoginThread = new Thread() {
			public void run() {
				if (needAuthentication) {
					boolean authen = authenticateApplication();
					if (!authen) {
						mHandler.sendEmptyMessage(LOGIN_FAILED);
						return;
					}
				}

				final JsonAuth login = JsonAuth.login(username, password);
				if (login.isNetworkError()) {
					mHandler.sendEmptyMessage(NO_NETWORK);
					return;
				}
				if (login.isSuccess()) {
//					if (!login.packageCode.equalsIgnoreCase("")) {
						// save Login info
						DataStore dataStore = DataStore.getInstance();
						if (!Util.checkStringIsemptyOrNull(login.phoneNumber)) {
							dataStore.setMsisdn(login.phoneNumber);
						}
						dataStore.setPassword(password);
						dataStore.updateAccountConfig(login.hashAccount);
						if (!username.equals(oldUsername)) {
							// mContext.deleteDatabase(DatabaseManager.DATABASE_NAME);
							DataStore.reinit(LoginActivity.this);
						}
						mHandler.sendEmptyMessage(LOGIN_SUCCESS);
//					} else {
//						if (login.message != null
//								&& !login.message.equalsIgnoreCase("")) {
//							mHandler.post(new Runnable() {
//
//								@Override
//								public void run() {
//									// TODO Auto-generated method stub
//									if (mProgressDialog != null
//											&& mProgressDialog.isShowing())
//										mProgressDialog.dismiss();
//									final ChaChaDialog dialog = new ChaChaDialog(
//											LoginActivity.this, null);
//									dialog.setTitle("Thông báo");
//									dialog.setMessage(login.message);
//									View.OnClickListener clickListener = new View.OnClickListener() {
//
//										@Override
//										public void onClick(View v) {
//											// TODO Auto-generated method stub
//											dialog.dismiss();
//											mApp.register(LoginActivity.this,
//													"", mHandler,
//													mApp.canTrialFuntion(),
//													closeRegisterClickListener);
//										}
//									};
//									dialog.addButton("OK", clickListener);
//									dialog.show();
//								}
//							});
//						}
//					}

				} else {
					if (login.getErrorCode() == 401) {
						ERROR_MSG = login.getErrorMessage();
						mHandler.sendEmptyMessage(LOGIN_FAILED_401);
					} else {
						mHandler.sendEmptyMessage(LOGIN_FAILED);
					}
				}
			}
		};

		mProgressDialog = new ChaChaProgressDialog(this);
		mProgressDialog.setTimeAutoHide(99999999);
		mProgressDialog
				.setMessage(getString(R.string.login_screen_login_in_progress));
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();
		doLoginThread.start();
	}

	private boolean authenticateApplication() {

		// Request random key
		JsonAuth ja = JsonAuth.requestAuthKey();

		if (ja.isNetworkError())
			return false;

		if (!ja.isSuccess()) {

			return false;
		}

		// validate
		JsonAuth validate = JsonAuth.validate(ja.randomKey);

		if (validate.isNetworkError()) {
			return false;
		}

		if (!validate.isSuccess()) {
			return false;
		}

		// authen success

		// save extra data here
		DataStore dataStore = DataStore.getInstance();
		dataStore.setConfig(Const.KEY_SMS_SERVER, validate.mService.sms_server);
		dataStore.setConfig(Const.KEY_SMS_CONTENT,
				validate.mService.sms_content);
		dataStore.setConfig(Const.KEY_TRIAL_SMS_CONTENT,
				validate.mService.trial_sms_content);
		dataStore.setConfig(Const.KEY_TRIAL_SMS_SERVER,
				validate.mService.trial_sms_server);

		Util mUtil = new Util(this);
		mUtil.setSharedPre(Const.KEY_SMS_SERVER, validate.mService.sms_server);
		mUtil.setSharedPre(Const.KEY_SMS_CONTENT, validate.mService.sms_content);
		mUtil.setSharedPre(Const.KEY_TRIAL_SMS_SERVER,
				validate.mService.trial_sms_server);
		mUtil.setSharedPre(Const.KEY_TRIAL_SMS_CONTENT,
				validate.mService.trial_sms_content);
		mUtil.setSharedPre(Const.KEY_ASK_RATE,
				Integer.toString(validate.mService.ask_rate));
		// mUtil.setSharedPre(Const.KEY_ASK_RATE, "1");
		mUtil.setSharedPre(Const.KEY_WARNING_MSG,
				validate.mService.warning_message);
		String temp = mUtil.getSharedPre(Const.KEY_LOGIN_COUNT);
		int curr_count = 0;
		try {
			if (temp.trim().equals(""))
				curr_count = 0;
			else
				curr_count = Integer.parseInt(temp);
		} catch (Exception e) {
			// TODO: handle exception
			curr_count = 0;
		}

		mUtil.setSharedPre(Const.KEY_LOGIN_COUNT, "" + (curr_count + 1));
		return true;
	}

	public void doGetPass(View view) {
		// SharedProperties mUtil = new SharedProperties(mContext);
		// SMS_TO = mUtil.getSharedPre(Const.KEY_SMS_SERVER);
		// SMS_BODY = mUtil.getSharedPre(Const.KEY_SMS_CONTENT);
		DataStore dataStore = DataStore.getInstance();
		SMS_TO = dataStore.getConfig(Const.KEY_SMS_CONTENT);
		SMS_BODY = dataStore.getConfig(Const.KEY_SMS_SERVER);
		if (!SMS_TO.trim().equals("") && !SMS_BODY.trim().equals("")) {
			// send message here
			final ChaChaDialog dialog = new ChaChaDialog(this, null);
			dialog.setTitle("Quên mật khẩu");
			dialog.setMessage("Bạn có muốn gửi tin nhắn với nội dung "
					+ SMS_BODY + " tới tổng đài " + SMS_TO
					+ " để lấy lại mật khẩu không ?");
			View.OnClickListener confirmClickListener = new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					sendSMS(SMS_TO, SMS_BODY);
				}
			};

			View.OnClickListener closeClickListener = new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			};
			dialog.addButton(this.getString(R.string.confirm_yes),
					confirmClickListener);
			dialog.addButton(this.getString(R.string.confirm_no),
					closeClickListener);
			dialog.show();
		} else {
			showAlert("Chức năng này đang được cập nhật");
		}
	}

	private void sendSMS(String phoneNumber, String message) {

		// call message composer

		Uri uri = Uri.parse("smsto:" + phoneNumber);
		Intent it = new Intent(Intent.ACTION_SENDTO, uri);
		it.putExtra("sms_body", message);
		startActivity(it);
	}

	RegisterListener registerListener = new RegisterListener() {
		
		@Override
		public void onRegisterSuccessListener() {
			// TODO Auto-generated method stub
			DataStore dataStore = DataStore.getInstance();
			dataStore.setConfig(Const.KEY_IS_LOGOUT, "false");
			Intent i = new Intent(LoginActivity.this, MainScreen.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			finish();
		}
		
		@Override
		public void onRegisterFailListener() {
			// TODO Auto-generated method stub
			
		}
	};


	@Override
	protected void logoutListener() {
		// TODO Auto-generated method stub
		// Do nothing here
	}

	@Override
	protected void unListenerLogout() {
		// TODO Auto-generated method stub
		// Do nothing here
	}

	// END-----------------------

}
